#pragma once

#include <cstdlib>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "log.hpp"
#include "err.hpp"

void Daemon(){
    //1.忽略信号
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);

    //2.让自己不要成为组长
    if(fork() > 0)
        exit(0);

    //3.新建会话
    pid_t ret = setsid();
    if((int)ret == -1){
        logMessage(Fatal, "daemon error, code: %d, string: %s", errno, strerror(errno));
        exit(SETSID_ERR);
    }

    //4.处理后续对标准输入输出0，1，2的问题
    int fd = open("/dev/null", O_RDWR);
    if(fd < 0){
        logMessage(Fatal, "open error, code: %d, string: %s", errno, strerror(errno));
        exit(OPEN_ERR);
    }

    dup2(fd, 0);
    dup2(fd, 1);
    dup2(fd, 2);
    close(fd);
}